import {
  Body,
  Controller,
  Delete,
  Get,
  Headers,
  Param,
  Patch,
  Post,
  Put,
  Query,
  Req,
  UseInterceptors,
} from '@nestjs/common';
import { Result } from '../../common/result/Result';
import { MenuService } from './menu.service';
import { MenuForm } from './dto/menu.form';
import {
  AuthInterceptor,
  RequiredPermission,
} from '../../config/filter/auth.interceptor';

@Controller('/api/v1/menus')
export class MenuController {
  constructor(private menuService: MenuService) {}

  /**
   * 路由列表
   */
  @Get('/routes')
  @UseInterceptors(AuthInterceptor)
  async getRoutes(): Promise<Result<any>> {
    const result = await this.menuService.getRoutes();
    return result;
  }

  /**
   * 菜单列表查询
   */
  @Get('')
  @UseInterceptors(AuthInterceptor)
  async listMenus(@Query('keywords') keywords: string): Promise<Result<any>> {
    const result = await this.menuService.listMenus(keywords);
    return result;
  }

  /**
   * 删除菜单
   * @param id
   */
  @Delete('/:id')
  @UseInterceptors(AuthInterceptor)
  @RequiredPermission('sys:menu:delete')
  async deleteMenu(@Param('id') id: number) {
    const result = await this.menuService.deleteMenu(id);
    return result;
  }

  /**
   * 新增菜单
   * @param form
   * @param token
   */
  @Post('')
  @UseInterceptors(AuthInterceptor)
  @RequiredPermission('sys:menu:add')
  async addMenu(
    @Body() form: MenuForm,
    @Headers('authorization') token: string,
  ) {
    const result = await this.menuService.addMenu(form, token);
    return result;
  }

  /**
   * 菜单下拉列表
   */
  @Get('/options')
  @UseInterceptors(AuthInterceptor)
  async listMenuOptions() {
    const result = await this.menuService.menuOptions();
    return result;
  }
  @Get('/:id/form')
  @UseInterceptors(AuthInterceptor)
  async getMenuForm(@Param('id') id: number) {
    const result = await this.menuService.getMenuForm(id);
    return result;
  }

  /**
   * 修改菜单信息
   * @param id
   * @param form
   * @param req
   */
  @Put('/:id')
  @UseInterceptors(AuthInterceptor)
  @RequiredPermission('sys:menu:edit')
  async updateMenu(
    @Param('id') id: number,
    @Body() form: MenuForm,
    @Req() req,
  ) {
    const result = await this.menuService.updateMenu(id, form, req.user);
    return result;
  }

  /**
   * 修改菜单显示状态
   * @param id
   * @param visible
   */
  @Patch('/:id')
  @UseInterceptors(AuthInterceptor)
  async updateMenuVisible(
    @Param('id') id: number,
    @Query('visible') visible: number,
  ) {
    const result = this.menuService.updateMenuVisible(id, visible);
    return result;
  }
}
